package com.uam.utils.file.analysis.help;

import com.uam.common.exception.UamException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.index.qual.SameLen;
import org.geotools.geojson.feature.FeatureJSON;
import org.geotools.kml.KMLConfiguration;
import org.geotools.xsd.PullParser;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Objects;

/**
 * @author heguanglong
 * kml转 geojson 做数据校验
 */
@Slf4j
public class Kml2GeoJson extends AnalysisParent implements File2GeoJson {
    @Override
    public RetAnalysisVo fileToGeoJsonFile(String fileUrl, String targetUrl, String fileName) throws IOException {
        FileInputStream input=null;
        try {
            input = new FileInputStream(fileUrl);
            PullParser parser = new PullParser(new KMLConfiguration(), input, SimpleFeature.class);
            FeatureJSON fjson = new FeatureJSON();
            StringWriter sw = new StringWriter();
            SimpleFeature simpleFeature = (SimpleFeature) parser.parse();
            sw.append("{    \"type\": \"FeatureCollection\",    \"features\": [");
            while (simpleFeature != null) {
                SimpleFeatureType featureType = simpleFeature.getFeatureType();
                fjson.setFeatureType(featureType);
                fjson.writeFeature(simpleFeature, sw);
                simpleFeature = (SimpleFeature) parser.parse();
                if (simpleFeature != null) {
                    sw.append(",");
                }
            }
            sw.append("]}");
            sw.close();
            return toGeoJsonFile(sw.toString(),targetUrl,fileName);
        } catch (Exception e) {
            log.error("KML 文件解析报错：{}", e.getMessage());
            throw UamException.fileTypeError("KML 文件解析报错");
        } finally {
            Objects.requireNonNull(input, "KML 文件输入流为空").close();
        }
    }
}
